import pycurl, json 
import urllib
import sqlite3
import sys
import signal

candidates = [3,'santorum','romney,','paul','gingrich','obama']
parties = [3,'democrat','republican','gop','right','left','green','libertarian','tea']
voting = [2,'2012','ballot','vote','voting','voted','votes','delegates','caucus','candidates','primaries','super','tuesday','win','victory',]
issues = [2,'economy','jobs','drilling','bailout','health','care','reform','tax','obamacare','welfare','muslim','abortion','drugs','energy','iraq','afghanistan','war','budget']
super_tuesday = ['Super Tuesday','super tuesday','#supertuesday','primary','primaries','alaska','georgia','idaho','massachusetts','north dakota','ohio','oklahoma','tennessee','vermont','virginia',]
set_list = [candidates,parties,voting,issues,]
economy = ['economy','taxes','tax','unemployment','jobs','job','fiscal policy','fiscal','economic','economy','banking','finance','financial','spending','raise tax', 'stimulus','wall street','recovery','employment','recession','business','small business']
health_care = ['health','health care', 'health', 'deathpanel','health care act','affordable health','health reform','doctor','patients','hospital','medicare','medicaid','insurance','premium','malpractice',]
foreign_policy = ['fpolicy','foreign policy','military','force','terrorist','attack','war','afghanistan','iraq','iran','korea','libya','war on terror','isreal','defense','defense department','overseas','negotiation','nations','withdraw','coalition','dictator','muslim','commander','threat','radical','islam','middle east','region',]
category_list = [economy,health_care,foreign_policy]

STREAM_URL = 'https://stream.twitter.com/1/statuses/filter.json'
dbconn = sqlite3.connect('./tweetz.db',check_same_thread=False)
cur = dbconn.cursor()
dbconn.isolation_level = None

def sig_int(signal,frame):
    print 'Ending brogram....'
    dbconn.commit()
    dbconn.close()
    sys.exit(0)


def attach_nozzle(callback,args):
    conn = pycurl.Curl()
    conn.setopt(pycurl.USERPWD,'madman92:madman18')
    conn.setopt(pycurl.URL,STREAM_URL)
    conn.setopt(pycurl.WRITEFUNCTION,callback)

    data = urllib.urlencode(args)
    conn.setopt(pycurl.POSTFIELDS,data)

    conn.perform()


def hose(data):
    score = 0
    bonus = 0

    tweet_dict =  json.loads(data)#['text'].lower()
    if 'text' in tweet_dict:
        tweet = tweet_dict['text'].lower()
        time_stamp = ''
        geo = ''
        screen_name = ''
        #tweet = 'Please vote 4 my entry in Contest of a Lifetime NEED 2500 VOTES by midnight EST. VOTE & SHARE PLEASE N THANKS :)'
        sanitized = tweet.split()


        if 'created_at' in tweet_dict:
            time_stamp = tweet_dict['created_at']

        if 'geo' in tweet_dict:
            geo  = tweet_dict['geo']
        if 'screen_name' in tweet_dict['user']:
            screen_name = tweet_dict['user']['screen_name']

        for s in set_list:
            tmp = scoreFromSet(sanitized,s)
            if tmp > 0:
                bonus = bonus + 1
            score = score + tmp
        score = score + bonus


        
        
            


        if score > 5:
            category = [0,'']
            for c in category_list:
                tmp =  categorizeTweet(tweet,c[1:])
                if tmp > category[0]:
                    category = (tmp,c[0])
                    print category
            lst = (tweet,screen_name,time_stamp,category[1],None,)
            #jprint category
            #$print category[1]
            cur.execute('INSERT into tweetz (tweet,sname,timestamp,category,location) VALUES (?,?,?,?,?)',lst)

def categorizeTweet(tweet,category):

    score = 0
    for element in category:
        if element in tweet:
            score  = score + 1
    return score




def scoreFromSet(tweet,set_name):
    match = list(set(tweet) & set(set_name[1:]))
    return set_name[0] * len(match)


if __name__== '__main__':
    signal.signal(signal.SIGINT,sig_int)
    args = { 'track':'election,vote,Santorum,Romney,Paul,Gingrich,Obama',
            }
    attach_nozzle(hose,args,)
    #f = open('./tweetz.out','r')
    #for line in f:
    #    if line != '\n':
            #hose(line)



